#include "StdFIFO.h"
#include <stdio.h>
#include <string.h>
//exit
#include <stdlib.h>
//定义相关
#include <sys/types.h>
//进程相关
#include <unistd.h>
//fcntl清除阻塞/open
#include <fcntl.h>
//FIFO
#include <sys/stat.h>
#include <StdFile.h>
//size_t
#include <stddef.h>

#define MaxSize 256
struct StdFIFO
{
    int fd;
    char pathName[MaxSize];
};

FIFO *InitFIFO(const char *path, OpenMode mode)
{
    FIFO* f = (FIFO*)malloc(sizeof(FIFO));
    if(f == NULL)
    {
        printf("FIFO malloc error!\n");
        return NULL;
    }

    strcpy(f->pathName,path);

    int ret = mkfifo(path,S_IWUSR | S_IRUSR);
    if(ret < 0)
    {
        perror("mkfifo");
    }

    f->fd = open(path,mode);
    if(f->fd < 0)
    {
        perror("open");
        free(f);
        return NULL;
    }
    return f;
}

void ReadFIFO(FIFO *f, void *ptr, size_t size)
{
    read(f->fd,ptr,size);
}

void WriteFIFO(FIFO *f, void *ptr, size_t size)
{
    write(f->fd,ptr,size);
}

void ClearFIFO(FIFO *f)
{
    if(f == NULL)
        return;
    
    char cmd[512] = {0};
    sprintf(cmd,"rm -f %s",f->pathName);
    system(cmd);
    free(f); 
}
